<template>
  <div class="process-entry-container">

    <!-- 主步骤导航栏 -->
    <div class="steps-navigation">
      <div
        v-for="(step, index) in steps"
        :key="index"
        class="step-item"
        :class="{
          'step-active': currentStep === index + 1,
          'step-completed': currentStep > index + 1,
          'step-disabled': currentStep < index + 1,
        }"
        @click="navigateToStep(index + 1)"
      >
        <div class="step-icon">
          <span v-if="currentStep > index + 1">✓</span>
          <span v-else>{{ index + 1 }}</span>
        </div>
        <div class="step-title">{{ step.title }}</div>
      </div>
    </div>

    <!-- 步骤内容区域 -->
    <div class="steps-content">
      <!-- ========== 修改：为所有步骤组件添加current-user属性 ========== -->
        <Step1
          v-if="currentStep === 1"
          :form-data="formData"
          :current-user="formData.currentUser"
          @next="nextStep"
          @update:form-data="updateFormData"
          @elder-saved="onElderSaved"
        />
      <Step2
        v-else-if="currentStep === 2"
        :form-data="formData"
        @next="nextStep"
        @prev="prevStep"
        @update:form-data="updateFormData"
      />
      <Step3
        v-else-if="currentStep === 3"
        :form-data="formData"
        :pending-task-id="route.query.pendingTaskId"
        @next="nextStep"
        @prev="prevStep"
        @update:form-data="updateFormData"
      />
      <Step4
        v-else-if="currentStep === 4"
        :form-data="formData"
        @next="nextStep"
        @prev="prevStep"
        @update:form-data="updateFormData"
      />
      <Step5
        v-else-if="currentStep === 5"
        :form-data="formData"
        @complete="completeProcess"
        @prev="prevStep"
        @update:form-data="updateFormData"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
// ========== 新增：导入用户store以获取登录用户信息 ==========
import { useUserStore } from "@/store/modules/user";
import Step1 from "./step1.vue";
import Step2 from "./step2.vue";
import Step3 from "./step3.vue";
import Step4 from "./step4.vue";
import Step5 from "./step5.vue";

const router = useRouter();
const route = useRoute();
// ========== 新增：创建用户store实例 ==========
const userStore = useUserStore();

// 主步骤配置
const steps = ref([
  { title: "申请入住" },
  { title: "入住评估" },
  { title: "入住审批" },
  { title: "入住配置" },
  { title: "签约办理" },
]);

// 当前步骤
const currentStep = ref(1);

// 表单数据
const formData = reactive({
  elderlyId: undefined,
  // ========== 新增：当前登录用户信息字段 ==========
  currentUser: {
    id: null,           // 用户ID
    nickName: "",       // 用户昵称
    name: "",          // 用户名
    roles: [],         // 用户角色
  },
  elder: {
    id: null,  // 新增：老人ID字段
    name: "",
    idCard: "",
    gender: "",
    birthDate: "",
    age: "",
    contact: "",
    address: "",
    ethnicity: "",
    politicalStatus: "",
    religiousBelief: "",
    maritalStatus: "",
    education: "",
    incomeSource: "",
    hobby: "",
    medicalInsurance: "",
    medicalCardNo: "",
    isDeleted: "1",
  },
  familyMembers: [
    {
      name: "",
      contact: "",
      relationship: "",
      isEmergency: "否",
    },
  ],
  uploads: {
    photo: null,
    idCardFront: null,
    idCardBack: null,
  },
  healthAssessment: {
    diseaseDiagnosis: [], // 疾病诊断（对应疾病情况）
    medicationInfo: [], // 用药情况
    riskFactors: [], // 风险因素（对应风险事件）
    woundCondition: [], // 伤口情况
    specialMedicalCare: [], // 特殊医疗照护情况
    selfCareAbility: [], // 自理能力
    dementiaPrecursors: [], // 痴呆前兆
    otherConditions: "", // 其他情况说明
    medicalReport: null, // 体检报告
    showOtherDisease: false, // 仅前端使用
    otherDisease: "", // 仅前端使用
  },
  // 修改后的 abilityAssessment 结构
  abilityAssessment: {
    selfCareAbility: [], // 自理能力评估
    mentalStatus: [], // 精神状态评估
    perceptionSocial: [], // 感知觉与社会参与
    answers: [], // 兼容旧字段
  },
  // 修改后的 assessmentReport 结构
  assessmentReport: {
    // 能力评估得分（从第二步自动计算）
    selfCareScore: 0, // 自理能力得分
    mentalStatusScore: 0, // 精神状态得分
    perceptionSocialScore: 0, // 感知与社会参与得分
    estimatedTotalScore: 0, // 预估总分
    preliminaryAbilityLevel: "", // 能力初步等级

    // 等级变更依据
    changeBasis: [], // 能力等级变更依据
    showOtherBasis: false, // 是否显示其他依据输入框
    otherBasis: "", // 其他变更依据

    // 最终等级
    finalLevel: "", // 能力最终等级

    // 评估信息
    assessmentDate: "", // 评估日期
    assessorId: null, // 评估人员ID
    assessmentStatus: "进行中", // 评估状态
  },
  admissionConfig: {
    duration: "",
    levelId: "",
    selectedBed: null,
  },
  feeConfig: {
    startDate: "",
    endDate: "",
    deposit: 0,
    careFee: 0,
    bedFee: 0,
    otherFee: 0,
    medicalInsurance: 0,
    governmentSubsidy: 0,
  },
  contractInfo: {
    contractNumber: "",
    contractName: "",
    contractStartDate: "",
    contractEndDate: "",
    signDate: "",
    partyCName: "",
    partyCContact: "",
    contractFile: null,
  },
});
// 监听子组件的老人保存事件
const onElderSaved = (elderId) => {
  formData.elderId = elderId;
  saveData();
};

// ========== 新增：解析并存储当前登录用户信息 ==========
const parseCurrentUserInfo = () => {
  try {
    // 检查用户store是否可用
    if (!userStore) {
      return;
    }
    
    // 从用户store获取当前登录用户信息
    const currentUser = {
      id: userStore.id || null,
      nickName: userStore.nickName || "",
      name: userStore.name || "",
      roles: userStore.roles || [],
    };
    
    // 更新formData中的用户信息
    formData.currentUser = currentUser;
    
    // 立即保存到本地存储
    saveData();
    
  } catch (error) {
    console.error("解析用户信息失败:", error);
  }
};

// ========== 新增：获取当前用户信息（供子组件使用） ==========
const getCurrentUserInfo = () => {
  return formData.currentUser;
};

// ========== 新增：刷新用户信息（当用户信息可能发生变化时调用） ==========
const refreshUserInfo = () => {
  parseCurrentUserInfo();
};

// 初始化数据
onMounted(() => {
  try {
    // ========== 新增：解析并存储当前登录用户信息 ==========
    parseCurrentUserInfo();

    // 从URL参数获取步骤
    if (route.query.step) {
      const step = parseInt(route.query.step);
      if (step >= 1 && step <= steps.value.length) {
        currentStep.value = step;
      }
    }

    // 从本地存储恢复数据
    const savedData = localStorage.getItem("admissionProcessData");
    if (savedData) {
      try {
        const parsedData = JSON.parse(savedData);
        Object.assign(formData, parsedData);
        // ========== 新增：确保用户信息是最新的（防止本地存储的用户信息过期） ==========
        parseCurrentUserInfo();
      } catch (parseError) {
        console.error("解析本地存储数据失败:", parseError);
        localStorage.removeItem("admissionProcessData");
      }
    }

    // 初始化风险事件和健康条件
    initializeFormData();

    // 生成合同编号
    if (!formData.contractInfo.contractNumber) {
      generateContractNumber();
    }
    
  } catch (error) {
    console.error("processEntry.vue 初始化失败:", error);
  }
});

// 初始化表单数据
const initializeFormData = () => {
  try {
    // 初始化风险事件（如果不存在）
    if (!formData.healthAssessment.riskEvents) {
      formData.healthAssessment.riskEvents = [
        { name: "跌倒", count: null },
        { name: "走失", count: null },
        { name: "噎食", count: null },
        { name: "自杀", count: null },
        { name: "昏迷", count: null },
      ];
    }

    // 初始化风险因素（与step2.vue兼容）
    if (!formData.healthAssessment.riskFactors) {
      formData.healthAssessment.riskFactors = [
        { name: "跌倒", count: null },
        { name: "走失", count: null },
        { name: "噎食", count: null },
        { name: "自杀", count: null },
        { name: "昏迷", count: null },
      ];
    } else {
      // 确保riskFactors数组结构与step2.vue期望的一致
      const expectedRiskEvents = [
        { name: "跌倒" },
        { name: "走失" },
        { name: "噎食" },
        { name: "自杀" },
        { name: "昏迷" },
      ];
      
      // 如果长度不匹配，重新初始化
      if (formData.healthAssessment.riskFactors.length !== expectedRiskEvents.length) {
        formData.healthAssessment.riskFactors = expectedRiskEvents.map(event => ({
          name: event.name,
          count: null
        }));
      }
    }

    // 初始化健康条件（如果不存在）
    if (!formData.healthAssessment.healthConditions) {
      formData.healthAssessment.healthConditions = [
        {
          name: "伤口情况",
          selected: [],
          showOther: false,
          otherText: "",
        },
        {
          name: "特殊医疗照护情况",
          selected: [],
          showOther: false,
          otherText: "",
        },
        {
          name: "自理能力",
          selected: [],
          showOther: false,
          otherText: "",
        },
        {
          name: "痴呆前兆",
          selected: [],
          showOther: false,
          otherText: "",
        },
      ];
    }

    // ========== 新增：初始化step2.vue需要的其他字段 ==========
    if (!formData.healthAssessment.diseaseDiagnosis) {
      formData.healthAssessment.diseaseDiagnosis = [];
    }
    if (!formData.healthAssessment.medicationInfo) {
      formData.healthAssessment.medicationInfo = [{ name: "", method: "", dosage: "" }];
    }
    if (!formData.healthAssessment.woundCondition) {
      formData.healthAssessment.woundCondition = [];
    }
    if (!formData.healthAssessment.specialMedicalCare) {
      formData.healthAssessment.specialMedicalCare = [];
    }
    if (!formData.healthAssessment.selfCareAbility) {
      formData.healthAssessment.selfCareAbility = [];
    }
    if (!formData.healthAssessment.dementiaPrecursors) {
      formData.healthAssessment.dementiaPrecursors = [];
    }
    if (!formData.healthAssessment.otherConditions) {
      formData.healthAssessment.otherConditions = "";
    }
    if (!formData.healthAssessment.medicalReport) {
      formData.healthAssessment.medicalReport = null;
    }
    if (!formData.healthAssessment.showOtherDisease) {
      formData.healthAssessment.showOtherDisease = false;
    }
    if (!formData.healthAssessment.otherDisease) {
      formData.healthAssessment.otherDisease = "";
    }
    if (!formData.healthAssessment.showOtherWound) {
      formData.healthAssessment.showOtherWound = false;
    }
    if (!formData.healthAssessment.otherWound) {
      formData.healthAssessment.otherWound = "";
    }
    if (!formData.healthAssessment.showOtherMedicalCare) {
      formData.healthAssessment.showOtherMedicalCare = false;
    }
    if (!formData.healthAssessment.otherMedicalCare) {
      formData.healthAssessment.otherMedicalCare = "";
    }
    if (!formData.healthAssessment.showOtherSelfCare) {
      formData.healthAssessment.showOtherSelfCare = false;
    }
    if (!formData.healthAssessment.otherSelfCare) {
      formData.healthAssessment.otherSelfCare = "";
    }
    if (!formData.healthAssessment.showOtherDementia) {
      formData.healthAssessment.showOtherDementia = false;
    }
    if (!formData.healthAssessment.otherDementia) {
      formData.healthAssessment.otherDementia = "";
    }

    // 初始化能力评估答案（如果不存在）
    if (!formData.abilityAssessment.answers || formData.abilityAssessment.answers.length === 0) {
      formData.abilityAssessment.answers = new Array(3).fill(null);
    }
    
  } catch (error) {
    console.error("初始化表单数据失败:", error);
  }
};

// 生成合同编号
const generateContractNumber = () => {
  const randomNum = Math.floor(1000000000 + Math.random() * 9000000000);
  formData.contractInfo.contractNumber = `HT${randomNum}`;
};

// 步骤导航
const navigateToStep = (step) => {
  if (step <= currentStep.value) {
    currentStep.value = step;
    updateUrl();
  }
};

const nextStep = () => {
  if (currentStep.value < steps.value.length) {
    currentStep.value++;
    updateUrl();
  }
  saveData();
};

const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
    updateUrl();
  }
  saveData();
};

// 更新URL以支持浏览器前进后退
const updateUrl = () => {
  router.replace({ query: { step: currentStep.value } });
};

// 更新表单数据
const updateFormData = (newData) => {
  if (newData) {
    Object.assign(formData, newData);
  }
  saveData();
};

// ========== 修改：保存数据到本地存储（添加用户信息保存日志） ==========
const saveData = () => {
  try {
    const dataToSave = JSON.stringify(formData);
    localStorage.setItem("admissionProcessData", dataToSave);
  } catch (error) {
    console.error("保存数据到本地存储失败:", error);
  }
};

// 完成流程
const completeProcess = () => {
  console.log("所有数据", formData);
  alert("签约办理完成！入住申请已成功提交。");
  // 清除本地存储
  localStorage.removeItem("admissionProcessData");
  // 重置表单
  resetFormData();
  currentStep.value = 1;
  updateUrl();
};

// ========== 修改：重置表单数据（保留用户信息不重置） ==========
const resetFormData = () => {
  Object.assign(formData, {
    // ========== 新增：保留当前用户信息，不重置 ==========
    currentUser: formData.currentUser,
    elder: {
      name: "",
      idCard: "",
      gender: "",
      birthDate: "",
      age: "",
      contact: "",
      address: "",
      ethnicity: "",
      politicalStatus: "",
      religiousBelief: "",
      maritalStatus: "",
      education: "",
      incomeSource: "",
      hobby: "",
      medicalInsurance: "",
      medicalCardNo: "",
    },
    familyMembers: [
      {
        name: "",
        contact: "",
        relationship: "",
        isEmergency: "否",
      },
    ],
    uploads: {
      photo: null,
      idCardFront: null,
      idCardBack: null,
    },
    healthAssessment: {
      diseases: [],
      showOtherDisease: false,
      otherDisease: "",
      medicines: [{ name: "", method: "", dosage: "" }],
      riskEvents: [],
      healthConditions: [],
      otherConditions: "",
      medicalReport: null,
    },
    abilityAssessment: {
      answers: [],
    },
    assessmentReport: {
      changeBasis: [],
      showOtherBasis: false,
      otherBasis: "",
      finalLevel: "",
    },
    admissionConfig: {
      duration: "",
      levelId: "",
      selectedBed: null,
    },
    feeConfig: {
      startDate: "",
      endDate: "",
      deposit: 0,
      careFee: 0,
      bedFee: 0,
      otherFee: 0,
      medicalInsurance: 0,
      governmentSubsidy: 0,
    },
    contractInfo: {
      contractNumber: "",
      contractName: "",
      contractStartDate: "",
      contractEndDate: "",
      signDate: "",
      partyCName: "",
      partyCContact: "",
      contractFile: null,
    },
  });
  initializeFormData();
  generateContractNumber();
};
</script>

<style scoped>
.process-entry-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

/* 主步骤导航样式 */
.steps-navigation {
  display: flex;
  justify-content: space-between;
  margin: 30px 0 50px;
  position: relative;
}

.steps-navigation::before {
  content: "";
  position: absolute;
  top: 18px;
  left: 50px;
  right: 50px;
  height: 2px;
  background-color: #e5e7eb;
  z-index: 1;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
  width: 20%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.step-item:hover:not(.step-disabled) {
  transform: translateY(-2px);
}

.step-icon {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background-color: #e5e7eb;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.step-title {
  font-size: 14px;
  color: #6b7280;
  transition: all 0.3s ease;
  text-align: center;
}

.step-active .step-icon {
  background-color: #3b82f6;
  color: white;
}

.step-active .step-title {
  color: #3b82f6;
  font-weight: 600;
}

.step-completed .step-icon {
  background-color: #10b981;
  color: white;
}

.step-completed .step-title {
  color: #10b981;
}

.step-disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

/* 步骤内容样式 */
.steps-content {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 30px;
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .steps-navigation {
    flex-direction: column;
    gap: 20px;
  }

  .step-item {
    width: 100%;
    flex-direction: row;
    gap: 12px;
  }

  .steps-navigation::before {
    display: none;
  }

  .steps-content {
    padding: 15px;
  }
}
</style>
